<template>
  <div class="realtime-monitoring">
    <!-- 连接状态指示器 -->
    <div class="connection-status" :class="connectionStatusClass">
      <div class="status-indicator">
        <i :class="statusIcon"></i>
        <span>{{ statusText }}</span>
      </div>
      <div class="last-update" v-if="lastUpdateTime">
        最后更新: {{ formatTime(lastUpdateTime) }}
      </div>
    </div>

    <!-- 实时数据展示 -->
    <div class="monitoring-data" v-if="monitoringData">
      <!-- 服务器状态 -->
      <div class="data-section">
        <h4><i class="fa fa-server"></i> 服务器状态</h4>
        <div class="server-stats">
          <div class="stat-item">
            <span class="label">Zabbix服务器:</span>
            <span class="value">
              {{ monitoringData.overview?.servers?.zabbix_connected || 0 }} /
              {{ monitoringData.overview?.servers?.zabbix_total || 0 }}
            </span>
          </div>
          <div class="stat-item">
            <span class="label">Grafana服务器:</span>
            <span class="value">
              {{ monitoringData.overview?.servers?.grafana_connected || 0 }} /
              {{ monitoringData.overview?.servers?.grafana_total || 0 }}
            </span>
          </div>
        </div>
      </div>

      <!-- 监控统计 -->
      <div class="data-section">
        <h4><i class="fa fa-chart-line"></i> 监控统计</h4>
        <div class="monitoring-stats">
          <div class="stat-item">
            <span class="label">监控主机:</span>
            <span class="value">{{ monitoringData.overview?.monitoring?.total_hosts || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="label">活跃告警:</span>
            <span class="value alert-count" :class="{ 'has-alerts': (monitoringData.overview?.monitoring?.active_alerts || 0) > 0 }">
              {{ monitoringData.overview?.monitoring?.active_alerts || 0 }}
            </span>
          </div>
        </div>
      </div>

      <!-- 告警分级 -->
      <div class="data-section" v-if="monitoringData.overview?.monitoring?.alert_severity">
        <h4><i class="fa fa-exclamation-triangle"></i> 告警分级</h4>
        <div class="alert-severity">
          <div class="severity-item high">
            <span class="label">严重:</span>
            <span class="value">{{ monitoringData.overview.monitoring.alert_severity.high || 0 }}</span>
          </div>
          <div class="severity-item medium">
            <span class="label">一般:</span>
            <span class="value">{{ monitoringData.overview.monitoring.alert_severity.medium || 0 }}</span>
          </div>
          <div class="severity-item low">
            <span class="label">轻微:</span>
            <span class="value">{{ monitoringData.overview.monitoring.alert_severity.low || 0 }}</span>
          </div>
        </div>
      </div>

      <!-- 最近告警 -->
      <div class="data-section" v-if="monitoringData.alerts && monitoringData.alerts.length > 0">
        <h4><i class="fa fa-bell"></i> 最近告警</h4>
        <div class="recent-alerts">
          <div
            v-for="alert in monitoringData.alerts.slice(0, 5)"
            :key="alert.id"
            class="alert-item"
            :class="alert.severity"
          >
            <div class="alert-info">
              <div class="alert-title">{{ alert.title }}</div>
              <div class="alert-host">{{ alert.hostname }}</div>
            </div>
            <div class="alert-time">{{ formatTime(alert.created_at) }}</div>
          </div>
        </div>
      </div>

      <!-- 主机状态 -->
      <div class="data-section" v-if="monitoringData.host_status && monitoringData.host_status.length > 0">
        <h4><i class="fa fa-desktop"></i> 主机状态</h4>
        <div class="host-status">
          <div
            v-for="host in monitoringData.host_status.slice(0, 8)"
            :key="host.id"
            class="host-item"
            :class="getHostStatusClass(host.availability)"
          >
            <div class="host-info">
              <div class="host-name">{{ host.hostname }}</div>
              <div class="host-ip">{{ host.ip_address }}</div>
            </div>
            <div class="host-status-indicator">
              <i :class="getHostStatusIcon(host.availability)"></i>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 控制按钮 -->
    <div class="controls">
      <button @click="requestUpdate" class="control-btn" :disabled="!isConnected">
        <i class="fa fa-refresh"></i>
        立即更新
      </button>
      <button @click="toggleConnection" class="control-btn">
        <i :class="isConnected ? 'fa fa-pause' : 'fa fa-play'"></i>
        {{ isConnected ? '断开' : '连接' }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { monitoringWebSocket } from '@/utils/websocket'
import type { MonitoringData } from '@/utils/websocket'
import { monitoringApi } from '@/api/monitoring'

// 响应式数据
const isConnected = ref(false)
const connectionStatus = ref('disconnected')
const monitoringData = ref<MonitoringData | null>(null)
const lastUpdateTime = ref<string | null>(null)

// 计算属性
const connectionStatusClass = computed(() => ({
  'status-connected': isConnected.value,
  'status-disconnected': !isConnected.value,
  'status-connecting': connectionStatus.value === 'connecting'
}))

const statusIcon = computed(() => {
  switch (connectionStatus.value) {
    case 'connected':
      return 'fa fa-circle text-success'
    case 'connecting':
      return 'fa fa-spinner fa-spin text-warning'
    default:
      return 'fa fa-circle text-danger'
  }
})

const statusText = computed(() => {
  switch (connectionStatus.value) {
    case 'connected':
      return '已连接'
    case 'connecting':
      return '连接中...'
    case 'closing':
      return '断开中...'
    default:
      return '未连接'
  }
})

// 方法
const updateConnectionStatus = () => {
  isConnected.value = monitoringWebSocket.isConnected
  connectionStatus.value = monitoringWebSocket.connectionState
}

const handleInitialData = (data: any) => {
  monitoringData.value = { overview: data, host_status: data.host_status || [] }
  lastUpdateTime.value = new Date().toISOString()
}

const handleMonitoringUpdate = (data: MonitoringData) => {
  monitoringData.value = data
  lastUpdateTime.value = new Date().toISOString()
}

// 主动获取监控数据
const loadMonitoringData = async () => {
  try {
    const response = await monitoringApi.getOverview()
    if (response.success) {
      monitoringData.value = {
        overview: response.data,
        host_status: response.data.host_status || []
      }
      lastUpdateTime.value = new Date().toISOString()
    }
  } catch (error) {
    console.error('获取监控数据失败:', error)
  }
}

const handleAlertNotification = (data: any) => {
  // 处理新告警通知
  console.log('收到新告警:', data)
  // 可以在这里添加通知逻辑
}

const requestUpdate = async () => {
  // 通过WebSocket请求更新
  monitoringWebSocket.requestUpdate()
  // 同时主动获取最新数据
  await loadMonitoringData()
}

const toggleConnection = async () => {
  if (isConnected.value) {
    monitoringWebSocket.disconnect()
  } else {
    try {
      await monitoringWebSocket.connect()
    } catch (error) {
      console.error('连接失败:', error)
    }
  }
  updateConnectionStatus()
}

const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getHostStatusClass = (availability: string) => {
  switch (availability) {
    case '1':
      return 'available'
    case '2':
    case '0': // 未监控状态也显示为不可用
      return 'unavailable'
    default:
      return 'unavailable' // 默认显示为不可用（红色）而不是未知
  }
}

const getHostStatusIcon = (availability: string) => {
  switch (availability) {
    case '1':
      return 'fa fa-check-circle text-success'
    case '2':
    case '0': // 未监控状态显示为离线
      return 'fa fa-times-circle text-danger'
    default:
      return 'fa fa-times-circle text-danger' // 默认显示为离线（红色）
  }
}

// 生命周期
onMounted(async () => {
  // 首先加载初始数据
  await loadMonitoringData()

  // 注册消息处理器
  monitoringWebSocket.on('initial_data', handleInitialData)
  monitoringWebSocket.on('monitoring_update', handleMonitoringUpdate)
  monitoringWebSocket.on('alert_notification', handleAlertNotification)

  // 连接WebSocket
  try {
    await monitoringWebSocket.connect()
    updateConnectionStatus()
  } catch (error) {
    console.error('初始连接失败:', error)
    updateConnectionStatus()
  }

  // 定期更新连接状态
  const statusInterval = setInterval(updateConnectionStatus, 1000)

  onUnmounted(() => {
    clearInterval(statusInterval)
    monitoringWebSocket.off('initial_data', handleInitialData)
    monitoringWebSocket.off('monitoring_update', handleMonitoringUpdate)
    monitoringWebSocket.off('alert_notification', handleAlertNotification)
  })
})
</script>

<style scoped>
.realtime-monitoring {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.connection-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  background: rgba(0, 0, 0, 0.2);
}

.status-connected {
  border-left: 4px solid #67c23a;
}

.status-disconnected {
  border-left: 4px solid #f56c6c;
}

.status-connecting {
  border-left: 4px solid #e6a23c;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  white-space: nowrap; /* 防止文字换行 */
  flex-shrink: 0; /* 防止收缩 */
}

.last-update {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.8rem;
}

.monitoring-data {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.data-section {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 16px;
}

.data-section h4 {
  color: #00eaff;
  margin: 0 0 12px 0;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.server-stats,
.monitoring-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.label {
  color: rgba(255, 255, 255, 0.7);
}

.value {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.alert-count.has-alerts {
  color: #f56c6c;
  font-weight: bold;
}

.alert-severity {
  display: flex;
  gap: 16px;
}

.severity-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  border-radius: 6px;
  min-width: 60px;
}

.severity-item.high {
  background: rgba(245, 108, 108, 0.2);
}

.severity-item.medium {
  background: rgba(230, 162, 60, 0.2);
}

.severity-item.low {
  background: rgba(103, 194, 58, 0.2);
}

.recent-alerts {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.alert-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid;
}

.alert-item.high {
  border-left-color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

.alert-item.medium {
  border-left-color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

.alert-item.low {
  border-left-color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
}

.alert-title {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  font-size: 0.9rem;
}

.alert-host {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.8rem;
}

.alert-time {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.8rem;
}

.host-status {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 8px;
}

.host-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  background: rgba(0, 0, 0, 0.2);
}

.host-item.available {
  border-left: 3px solid #67c23a;
}

.host-item.unavailable {
  border-left: 3px solid #f56c6c;
}

.host-item.unknown {
  border-left: 3px solid #e6a23c;
}

.host-name {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  font-size: 0.9rem;
}

.host-ip {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.8rem;
}

.controls {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.control-btn {
  background: rgba(164, 244, 186, 0.15);
  border: 1px solid rgba(164, 244, 186, 0.3);
  color: rgba(255, 255, 255, 0.9);
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.control-btn:hover:not(:disabled) {
  background: rgba(164, 244, 186, 0.25);
  border-color: rgba(164, 244, 186, 0.5);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}
</style>
